//
//  GameViewController.swift
//  swiftDemo
//
//  Created by Gerry on 2022/1/7.
//

import UIKit
import RxCocoa

let kNumberOfRow : CGFloat = 4

class GameViewController: UIViewController {
    
    private var viewModel : GameViewModel = GameViewModel()

    private lazy var collectionView : UICollectionView = { [unowned self] in
        let layout = UICollectionViewFlowLayout()
        
        let collectionView = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.backgroundColor = UIColor.init(r: 240, g: 240, b: 240)
        collectionView.register(GameCell.self, forCellWithReuseIdentifier: "GameCell")
        
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

//        view.backgroundColor = UIColor.yellow
        setupUI()
        
        viewModel.requestData { isSuccess, message in
            self.collectionView.reloadData()
        }
    }
    
}

extension GameViewController  {
    func setupUI() {
        view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
    }
}


extension GameViewController : UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.gameModels.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell : GameCell = collectionView.dequeueReusableCell(withReuseIdentifier: "GameCell", for: indexPath) as! GameCell

        cell.setGameModel(model: self.viewModel.gameModels[indexPath.item])
        
//        cell.backgroundColor = kRandomColor
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = (kScreenW - 20.0) / kNumberOfRow
        let height = width * 3 / 4.0
        return CGSize.init(width: width, height: height)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 10, left: 10, bottom: 10, right: 10)
    }
    
    
}

